// 网关配置的前缀
let account_server = "/accountSer"

// let userId = "200031"
// let userName = "YANGRANT"
let userId = ""
let userName = ""

var currentPage = 1;    // 当前页
var pageSize = 10;      // 页大小
var total = 0;          // 数据总量
var pages = 1;          // 页数总量

let search_value = "";

let Authorization = "";
let refreshToken = "";

// 加载页面时读取后台的 ip
window.onload = function () {
    let accountStatus = $("#accountStatus").html();
    // console.log(accountStatus);
    if(accountStatus !== "正常"){
        $("#forbidden").removeAttr("hidden");
    }

    let authorities = $("#authorities").html();
    unauthorized_2(authorities, "advertisement");

    $.ajaxSettings.async = false;
    $.getJSON("/js/properties.json", function (data) {
        account_server = data.accountServer;
    });
    // 获取令牌
    Authorization = getCookie("Authorization")
    refreshToken = getCookie("refreshToken")
    userId = $("#userId").html();
    userName = $("#userName").html();
    getAdvList(currentPage, pageSize, "")
}

// 获得 广告等级
function getAdvList(currentPage, pageSize, search_value) {
    $.ajax({
        type: "get",
        async: false,
        url: account_server + "/account/advertise",
        data: {
            currentPage: currentPage,
            pageSize: pageSize,
            searchValue: search_value,
        },
        success: function (data) {
            console.log("广告列表 - 第 " + currentPage + " 页");
            total = data.datas.total;
            pageSize = data.datas.size;
            pages = data.datas.pages;

            $("#total").html(total);
            //清空数据
            $("#advList").empty();
            //返回的数据用data.rows获取内容
            $.each(data.datas.records, function (i, item) {
                $("#advList").append(
                    "<div class='col-lg-12 mb-20'>" +
                    "<div class='single-job style-two'>" +
                    "<div class='info-top'>" +
                    "<div class='job-info'>" +
                    "<div class='job-info-inner'>" +
                    "<div class='job-info-top'>" +
                    "<div class='saveJob for-listing>'" +
                    "<a class='job-type-label ml-20'>优先级</a>" +
                    " <span class='featured-label mr-20' style='margin: -3px 0 0 10px;'>" + item.level + "</span>" +
                    "</div>" +
                    "<div class='title-name'>" +
                    "<h3 class='job-title'>" +
                    "<a>" + item.companyName + "</a>" +
                    "</h3>" +
                    "</div>" +
                    "</div>" +
                    "<div class='job-meta-two'>" +
                    "<div class='field-salary_from'>" +
                    "优先级 ：<span>" + item.level + "</span>" +
                    "</div>" +
                    "<div class='field-datetime'>" +
                    "<i class='lnr lnr-clock'></i>" +
                    "合作起始日期：<span>" + item.startDate + "</span>" +
                    "</div>" +
                    "<div class='field-map'>" +
                    "<i class='lnr lnr-clock'></i>" +
                    "结束日期：<span>" + item.endDate + "</span>" +
                    "</div>" +
                    "</div>" +
                    "<div class='ad-img'>" +
                    "<img src='" + item.photo + "'>" +
                    "</div>" +
                    "<div class='ad-but-area-1'>" +
                    "<button onclick='delAdv(\"" + item.id + "\")' class='col-md-7 btn btn-danger btn-default btn-sm ad-but' onClick=''>删除</button>" +
                    "<button onclick='updateAdv(\"" + item.id + "\",\"null\", \"photo\")' class='col-md-7 btn btn-warning btn-default btn-sm ad-but'>修改广告内容</button>" +
                    "<button onclick='updateAdv(\"" + item.id + "\",\"" + item.startDate + "\", \"data\")' class='col-md-7 btn btn-success btn-default btn-sm ad-but'>延长合作期限</button>" +
                    "</div>" +
                    "</div>" +
                    "</div>" +
                    "</div>" +
                    "</div>" +
                    "</div>"
                );
            });

            // pageMe.js 使用方法
            $("#page").paging({
                pageNum: currentPage, // 当前页面
                totalNum: pages, // 总页码
                totalList: total, // 记录总数量
                pageSize: pageSize,
                callback: function (num, size) { //回调函数
                    pageSize = size;
                    currentPage = num;
                    getAdvList(num, size, search_value)
                    // 返回顶部
                    if ($(window).scrollTop() > 200) {
                        $('body,html').animate({
                            scrollTop: 0
                        });
                    }
                }
            });
        },
        error: function (err) {
            // 异常
            cocoMessage.error(2000, err.statusText);
        }
    });
}

// 搜索框
function click_search() {
    search_value = $('#search').val();
    if (search_value === "" || search_value === null) {
        search_value = "";
    }
    getAdvList(1, pageSize, search_value);
}

function updateAdv(id, startDate, type) {
    let UUID = "";
    $.confirm({
        title: '提示',
        content: "确定要修改当前记录吗？",
        onContentReady: function () {
            var self = this;
            console.log(type)
            if (type === "data") {
                self.setContentAppend(
                    "<div class='single-input mb-25'>" +
                    "<label>截至时间 <span>*</span></label>" +
                    "<input type='text' id='endData' name='endData' readonly>" +
                    "<div class='error' id='error_endData'></div>" +
                    "<script type='text/javascript'>" +
                    "$('#endData').datetimepicker({" +
                    " language: 'zh-CN'," +
                    "format: 'yyyy-mm-dd hh:ii'," +
                    "weekStart: 1," +
                    "todayBtn: 1," +
                    "autoclose: 1," +
                    "todayHighlight: 1," +
                    "startView: 4," +
                    "minView: 0," +
                    "forceParse: 0," +
                    "hours12: false," +
                    "startDate:\"" + startDate + "\"" +
                    "})" +
                    "<\/script>" +
                    "</div>"
                )
            } else if (type === "photo") {
                UUID = createUUID();
                self.setContentAppend(
                    "<form action='/companySer/company/image' id='uploadPhoto'" +
                    "encType='multipart/form-data' method='post'>" +
                    "<div class='col-xl-10'>" +
                    "<div class='single-input mb-25'>" +
                    "<label>广告图片 <span>*</span></label>" +
                    "<div class='create-photo-left'>" +
                    "<label class='btn create-photo-left form-group' id='photo-logo'>" +
                    "<input type='file' id='photo' name='photo' class='photo'" +
                    "style='left:-9999px;position:absolute;'>" +
                    "<p class='fa fa-camera' style='margin-top: 20px'>" +
                    "<br>选择图片" +
                    "</p>" +
                    "</label>" +
                    " </div>" +
                    "<input type='text' name='type' value='advertisementPhoto' hidden>" +
                    "<input type='text' id='uuid' name='userId' value='" + UUID + "' hidden>" +
                    "</div>" +
                    "</div>" +
                    "</form>" +
                    "<script>" +
                    "$('input[name=\"photo\"]').change(function (event) {" +
                    "var ele = event.target;" +

                    "if (!/.(gif|jpg|jpeg|png|GIF|JPG|bmp)$/.test(ele.value)) {" +
                    "alert('图片类型必须是.gif,jpeg,jpg,png,bmp中的一种');" +
                    "return false;" +
                    "}" +

                    "var files = ele.files;" +
                    "if (files && files.length <= 0) {" +
                    "alert('出错了，请重新上传。')" +
                    "}" +

                    "var file = files[0];" +
                    "console.log('上传了照片');" +

                    "var path = URL.createObjectURL(file);" +
                    " $('.create-photo-left').css('background-image', 'url('+ path +')')" +
                    ".css('background-repeat', 'no-repeat')" +
                    ".css('background-size', '100% 100%');" +
                    "$('#photo-logo *').hide();" +

                    "$('#uploadPhoto').ajaxSubmit({" +
                    "datatype: 'json'," +
                    "success: function (res) {" +
                    "cocoMessage.info(2000, '图片上传成功', function () {" +
                    "});" +
                    "}," +
                    "error: function (res) {" +
                    "cocoMessage.error(2000, '图片上传出错，请重试', function () {" +
                    "});" +
                    "}" +
                    "});" +
                    "});" +
                    "<\/script>"
                )
            }
        },
        type: 'green',
        theme: "modern",
        closeAnimation: 'scaleY',
        buttons: {
            ok: {
                text: '确认',
                btnClass: 'btn-warning',
                action: function () {
                    let endDate = $('#endData').val();
                    if (endDate === null || endDate === "") {
                        endDate = "";
                    }

                    $.ajax({
                        type: "POST",
                        async: false,
                        url: account_server + "/account/advertise",
                        headers: {
                            "Content-Type": "application/json",
                            "Authorization": Authorization,
                            "refreshToken": refreshToken,
                        },
                        data: JSON.stringify({
                            "id": id,
                            "endDate": endDate,
                            "optionId": userId,
                            "optionName": userName,
                            "photoId": UUID,
                        }),
                        success: function (data) {
                            unauthorized(data);
                            if (data.resp_code === 0) {
                                // 成功
                                cocoMessage.info(2000, data.resp_msg, function () {
                                });
                            } else {
                                // 失败
                                cocoMessage.error(2000, data.resp_msg, function () {
                                });
                            }
                        },
                        error: function (err) {
                            // 异常
                            cocoMessage.error(2000, err.statusText, function () {
                                console.log(err);
                            });
                        }
                    })
                }
            },
            cancel: {
                text: '取消',
                btnClass: 'btn-default'
            }
        }
    });
}

function random() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}

function createUUID() {
    return (random() + random() + "-" + random() + "-" + random() + "-" + random() + random());
}

function delAdv(id) {
    $.confirm({
        title: '提示',
        content: "确定要删除当前记录吗？",
        type: 'green',
        theme: "modern",
        closeAnimation: 'scaleY',
        buttons: {
            ok: {
                text: '确认',
                btnClass: 'btn-warning',
                action: function () {
                    $.ajax({
                        type: "DELETE",
                        async: false,
                        url: account_server + "/account/advertise?id="+id,
                        headers: {
                            "Content-Type": "application/json",
                            "Authorization": Authorization,
                            "refreshToken": refreshToken,
                        },
                        success: function (data) {
                            unauthorized(data);
                            if (data.resp_code === 0) {
                                // 成功
                                cocoMessage.info(2000, data.resp_msg, function () {
                                });
                                location.reload();
                            } else {
                                // 失败
                                cocoMessage.error(2000, data.resp_msg, function () {
                                });
                            }
                        },
                        error: function (err) {
                            // 异常
                            cocoMessage.error(2000, err.statusText, function () {
                                console.log(err);
                            });
                        }
                    })
                }
            },
            cancel: {
                text: '取消',
                btnClass: 'btn-default'
            }
        }
    });
}
